<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
        integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
        integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
        crossorigin="anonymous"></script>
</head>
<style>
    .table-goods {
        width: 70%;
        margin: auto;
    }

    .table-nnss {
        width: 70%;
        margin: auto;
        margin-top: 50px;
    }

    th,
    td {
        text-align: center;
    }

    #but {
        margin-left: 45%;
        margin: 20px 45% 20px 45%;
    }

    a:link {
        color: black;
    }

    a:visited {
        color: grey;
    }

    a:hover {
        color: aqua;
    }

    a:active {
        color: pink;
    }

    p {
        text-align: center;
        font-size: 24px;
    }
</style>

<body>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" id="but">
        添加水果
    </button>
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="exampleInputPassword1">商品名称</label>
                        <input type="text" class="form-control" id="goodsname" placeholder="商品名称" value="苹果">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputPassword1">商品价格</label>
                        <input type="number" class="form-control" id="goodsprice" placeholder="商品价格" value="10">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputPassword1">商品库存</label>
                        <input type="number" class="form-control" id="goodsstock" placeholder="商品库存" value="100">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="saveGoods">发布</button>
                </div>
            </div>
        </div>
    </div>
    <div>
        <table class="table table-striped table-bordered table-hover table-condensed table-goods">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>商品名称</th>
                    <th>商品价格</th>
                    <th>商品库存</th>
                    <th>商品操作</th>
                </tr>
            </thead>
            <tbody id="tbody-goodsList"></tbody>
        </table>
    </div>
    <table class="table table-striped table-bordered table-hover table-condensed table-nnss">
        <thead>
            <tr>
                <th><input type="checkbox" id="all"></th>
                <th>ID</th>
                <th>商品名称</th>
                <th>商品价格</th>
                <th>商品库存</th>
                <!-- <th>商品操作</th> -->
            </tr>
        </thead>
        <tbody id="tbody-shopCar"></tbody>
    </table>
    <p>总价：<span></span></p>
</body>
<script src="./购物车plus.js"></script>
<script>
    var goodsList = [],
        shopCarList = []
    $(function () {
        $('#saveGoods').click(saveGoods)
        showGoodsList()
        shopCar()
        $('#tbody-goodsList').dblclick(deltGoodsList)
    })
    function saveGoods() {
        // 获取 input 框里的值
        var goodsname = $('#goodsname').val()
        var goodsprice = $('#goodsprice').val()
        var goodsstock = $('#goodsstock').val()
        var goodsData = {
            id: getGoodsId(),
            goodsname: goodsname,
            goodsprice: goodsprice,
            goodsstock: goodsstock
        }
        goodsList = getOrSetData('goodsList', goodsData)
        goodsList.push(goodsData)
        localStorage.setItem('goodsList', JSON.stringify(goodsList))
        showGoodsList()
    }
    // 添加商品类表
    function showGoodsList() {
        goodsList = getOrSetData('goodsList')
        var strHtml = ''
        for (let i in goodsList) {
            strHtml += `<tr>
                            <td>${goodsList[i].id}</td>
                            <td data-index='${i}' data-keys="name">${goodsList[i].goodsname}</td>
                            <td data-index='${i}' data-keys="price">${goodsList[i].goodsprice}</td>
                            <td data-index='${i}' data-keys="stock">${goodsList[i].goodsstock}</td>
                            <td><a href='#' onclick="delGoods(${i})">删除</a>&emsp;|&emsp;
                                <a href='#' onclick="showCar(${i})">加入购物车</a></td>
                        </tr>`
        }
        $('#tbody-goodsList').html(strHtml)
    }
    // 删除
    function delGoods(index) {
        // console.log(goodsList);
        // goodsList.splice(index, 1)
        // localStorage.setItem('goodsList', JSON.stringify(goodsList))
        // showGoodsList()
        let shopIndex = shopCarList.findIndex(function (item) {
            return item.id == goodsList[index].id
        })
        if (shopIndex > -1) {
            delData('shopCarList', shopIndex)
        }
        delData('goodsList', index)
        showGoodsList()
        shopCar()
    }
    // 编辑
    function deltGoodsList() {
        if (event.target.nodeName == 'TD') {
            // console.log($(event.target).html());
            if ($(event.target).attr('data-index') > -1) {
                let index = $(event.target).attr('data-index'),
                    keys = $(event.target).attr('data-keys')
                let inpHtml = `<input type="text" keys="${keys}" onblur="saveData(this,${index})" value="${$(event.target).html()}">`
                $(event.target).html(inpHtml)
            }
        }
    }
    // 编辑商品
    function saveData(obj, index) {
        let val = $(obj).val(),
            keys = $(obj).attr('keys'),
            shopCarIndex = shopCarList.findIndex(function (item) {
                return item.id == goodsList[index].id
            })
        if (keys == 'name') {
            goodsList[index].goodsname = val
            shopCarList[shopCarIndex].name = val
        } else if (keys == 'price') {
            goodsList[index].goodsprice = val
            shopCarList[shopCarIndex].price = val
        } else {
            goodsList[index].goodsstock = val
            shopCarList[shopCarIndex].stock = val
        }
        setData('goodsList', goodsList)
        showGoodsList()

        setData('shopCarList', shopCarList)
        shopCar()
    }
    // 加入购物车
    function showCar(index) {
        let shopIndex = shopCarList.findIndex(function (item) {
            // return item.id == goodsList[index].id
            if (item.id == goodsList[index].id) {
                return true
            }
        })
        if (shopIndex > -1) {
            shopCarList[shopIndex].num++
            setData('shopCarList', shopCarList)
        } else {
            let data = {
                id: goodsList[index].id,
                name: goodsList[index].goodsname,
                price: goodsList[index].goodsprice,
                num: 1,
                status: false
            }
            addData('shopCarList', data)
            shopCar()
        }

        shopCarList = getOrSetData('shopCarList', shopCarList)
        shopCar()
    }
    // 下面的那个商品表格
    function shopCar() {
        shopCarList = getOrSetData('shopCarList')
        // console.log(shopCarList, 123123)
        var strHtmlGoods = ''
        for (let i in shopCarList) {
            let check = shopCarList[i].status ? 'checked' : ''
            strHtmlGoods += `<tr>
                                <td><input type="checkbox" data-id onchange="amount(),upStatus(this,${i})" ${check}></td>
                                <td>${shopCarList[i].id}</td>
                                <td>${shopCarList[i].name}</td>
                                <td id="preceGoods">${shopCarList[i].price}</td>
                                <td>
                                    <input type="button" value="-" onclick="subtract(${i},this)">
                                    <input type="number" min="0" data-id="${i}" value="${shopCarList[i].num}" id="numGoods">
                                    <input type="button" value="+" onclick="add(${i},this)">
                                </td>
                            </tr>`
        }
        $('#tbody-shopCar').html(strHtmlGoods)
    }
    // 全选
    $('#all').change(function () {
        $('#tbody-shopCar input:checkbox').prop('checked', $(this).prop('checked'))
        for (let i in shopCarList) {
            shopCarList[i].status = $(this).prop('checked')
        }
        setData('shopCarList', shopCarList)
        amount()

    })
    // 全选状态
    function upStatus(obj, index) {
        shopCarList[index].status = $(obj).prop('checked')
        setData('shopCarList', shopCarList)
    }

    // 减
    function subtract(index, obj) {
        if (shopCarList[index].num <= 0) {
            $(obj).prop('disabled', true)
            alert('您预购的商品不能低于零件')
            return
        }
        // shopCarList[index].num--
        // setData('shopCarList', shopCarList)
        // shopCar()
        let goodsIndex = goodsList.findIndex(function (item) {
            return item.id == shopCarList[index].id
        })
        shopCarList[index].num--
        goodsList[goodsIndex].goodsstock++
        setData('goodsList', goodsList)
        setData('shopCarList', shopCarList)
        showGoodsList()
        shopCar()
        $(obj).next().val(shopCarList[index].num)
        setData('shopCarList', shopCarList)
        amount()
        showGoodsList()
    }
    // 加
    function add(index, obj) {
        // $(obj).prev().prop('disabled', false)
        // shopCarList[index].num++
        // setData('shopCarList', shopCarList)
        // amount()
        // shopCar()
        let goodsIndex = goodsList.findIndex(function (item) {
            return item.id == shopCarList[index].id
        })
        if (goodsList[goodsIndex].goodsstock <= 0) {
            return alert('库存不足')
        }
        shopCarList[index].num++
        goodsList[goodsIndex].goodsstock--
        setData('goodsList', goodsList)
        setData('shopCarList', shopCarList)
        $(obj).prev().val(++shopCarList[index].num)
        amount()
        showGoodsList()
        shopCar()
    }
    // 计算金额
    function amount() {
        var total = 0
        $('#tbody-shopCar input:checkbox').each(function (index, item) {
            if ($(item).prop('checked')) {
                // total += parseInt($('#priceGoods').html()) * $('#numGoods').val()
                total += shopCarList[index].price * shopCarList[index].num
            }
        })
        $('p span').html(total)
    }
    // 增加ID
    function getGoodsId() {
        var id = localStorage.getItem('goodsId') ?? 0
        localStorage.setItem('goodsId', ++id)
        return id
    }
    // 本地存储
    function getOrSetData(key, data = null, isPush = false) {
        // 存
        var localData = localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key)) : []
        // 取
        if (data) {
            if (isPush) {
                localData.push(data)
                localStorage.setItem(key, JSON.stringify(localData))
            } else {
                localStorage.setItem(key, JSON.stringify(data))
            }
        }
        // 结果
        return localData
    }
</script>

</html>